package com.frame.project.controller.system.dept;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.frame.common.constant.UserConstants;
import com.frame.common.utils.StringUtils;
import com.frame.framework.aspectj.lang.annotation.Log;
import com.frame.framework.aspectj.lang.enums.BusinessType;
import com.frame.framework.web.controller.BaseController;
import com.frame.framework.web.domain.Ztree;
import com.frame.framework.web.error.WebError;
import com.frame.project.domain.system.dept.Dept;
import com.frame.project.domain.system.role.Role;
import com.frame.project.service.system.dept.DeptService;

/**
 * @className ：DeptController
 * @describe ：部门信息
 */
@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController
{
    private String prefix = "system/dept";

    @Autowired
    private DeptService deptService;

    @RequiresPermissions("system:dept:view")
    @GetMapping()
    public String dept()
    {
        return prefix + "/dept";
    }

    @RequiresPermissions("system:dept:list")
    @PostMapping("/list")
    @ResponseBody
    public List<Dept> list(Dept dept)
    {
        List<Dept> deptList = deptService.selectDeptList(dept);
        return deptList;
    }

    /**
     * 新增部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, Model model)
    {
    	Dept dept = new Dept();
    	if(parentId == 0L) {
    		dept = deptService.findByParentId(parentId);
    	}else {
    		dept = deptService.findById(parentId);
    	}
    	model.addAttribute("dept", dept);
        return prefix + "/add";
    }

    /**
     * 新增保存部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public WebError addSave(@Validated Dept dept)
    {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error(-1,"新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        
        return deptService.insertDept(dept);
    }

    /**
     * 修改
     */
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, Model model)
    {
    	deptService.checkDeptDataScope(deptId);
        Dept dept = deptService.findById(deptId);
        model.addAttribute("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 保存
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:dept:edit")
    @PostMapping("/edit")
    @ResponseBody
    public WebError editSave(@Validated Dept dept)
    {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error(-1,"修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getId()))
        {
            return error(-1,"修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getId()) > 0)
        {
            return error(-1,"该部门包含未停用的子部门！");
        }
        deptService.updateDept(dept);
        return success();
    }

    /**
     * 删除
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:dept:remove")
    @GetMapping("/remove/{deptId}")
    @ResponseBody
    public WebError remove(@PathVariable("deptId") Long deptId)
    {
        if (deptService.selectDeptCountByParent(deptId) > 0)
        {
            return error(-1,"存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return error(-1,"部门存在用户,不允许删除");
        }
        
        deptService.delete(deptId);
        return success();
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(Dept dept)
    {
        return deptService.checkDeptNameUnique(dept);
    }

    /**
     * 选择部门树
     */
    @GetMapping("/selectDeptTree/{deptId}")
    public String selectDeptTree(@PathVariable("deptId") Long deptId, Model model)
    {
    	if(deptId == 0L) {
    		model.addAttribute("dept", deptService.findByParentId(deptId));
    	}else {
    		
    		model.addAttribute("dept", deptService.findById(deptId));
    	}
        return prefix + "/tree";
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        List<Ztree> ztrees = deptService.selectDeptTree(new Dept());
        return ztrees;
    }

    /**
     * 加载角色部门（数据权限）列表树
     */
    @GetMapping("/roleDeptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData(Role role)
    {
        List<Ztree> ztrees = deptService.roleDeptTreeData(role);
        return ztrees;
    }
}
